# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packagetool import PackageTool


class Proto:
    downloading_files = {}

    def download_file(self, do_send, url, callback):
        Proto.downloading_files[url] = {
            "callback": callback,
            "total_size": 0,
            "blocks": {},
            "data": None,
        }
        pt = PackageTool()
        pt.put_string(url)
        do_send(pt)

    def on_download_file(self, pt):
        url = pt.get_string()
        success = pt.get_bool()
        if url in Proto.downloading_files:
            df = Proto.downloading_files[url]

            if success:
                df["total_size"] = pt.get_uint32()
                offset = pt.get_uint32()
                size = pt.get_uint32()
                df["blocks"][offset] = size
                if not df["data"]:
                    df["data"] = bytearray(df["total_size"])
                data = pt.get_byte_array()
                df["data"][offset : offset + size] = data
                p = 0
                while True:
                    if p in df["blocks"]:
                        p=df["blocks"][p]
                    elif p == df["total_size"]:
                        df["callback"](url, df["total_size"], df["data"])
                        break
                    else:
                        df["callback"](url, -1, None)
                        break
            else:
                df["callback"](url, -1, None)


class Platform:
    @staticmethod
    def is_ubuntu_20_04():
        try:
            with open("/etc/os-release", "r") as f:
                content = f.read()
                return "ID=ubuntu" in content and 'VERSION_ID="20.04"' in content
        except FileNotFoundError:
            return False

    @staticmethod
    def is_ohos(self):  # todo
        return False
